#!/bin/bash
# 集群自动化部署脚本
# 功能：自动部署Web集群环境（NFS共享存储、MySQL数据库、Web节点、负载均衡）

# 配置区域 ======================================================
# 服务器列表（根据实际IP修改）
declare -A SERVERS=(
    ["web1"]="192.168.1.111"
    ["web2"]="192.168.1.112"
    ["web3"]="192.168.1.113"
    ["mysql"]="192.168.1.114"
    ["nfs"]="192.168.1.115"
    ["lb"]="192.168.1.116"
)

# 通用配置
USER="root"
PASSWORD="1"
SSH_OPTS="-o StrictHostKeyChecking=no -o ConnectTimeout=5"
LOG_FILE="cluster_deploy.log"

# 数据库配置
DB_NAME="testDB"
DB_USER="egon"
DB_PASS="123"

# 函数区域 ======================================================

# 初始化日志
init_log() {
    echo "=== 集群部署开始 $(date) ===" > $LOG_FILE
}

# 记录日志
log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') $1" | tee -a $LOG_FILE
}

# 检查命令执行结果
check_result() {
    if [ $? -ne 0 ]; then
        log "[错误] $1 执行失败!"
        exit 1
    fi
}

# SSH命令执行函数
ssh_cmd() {
    ssh $SSH_OPTS $USER@$1 "$2"
    check_result "在 $1 上执行命令: $2"
}

# 基础环境配置
setup_base() {
    log ">>> 正在设置所有节点基础环境"
    for host in "${!SERVERS[@]}"; do
        ip=${SERVERS[$host]}
        
        log "正在配置 $host ($ip)"
        
        # 设置主机名
        ssh_cmd $ip "hostnamectl set-hostname $host"
        
        # 关闭防火墙
        ssh_cmd $ip "systemctl stop firewalld && systemctl disable firewalld"
        
        # 禁用SELinux
        ssh_cmd $ip "setenforce 0 && sed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/selinux/config"
        
        # 安装基本工具
        ssh_cmd $ip "yum install -y wget net-tools epel-release"
    done
}

# NFS服务配置（根据test.sh格式重写）
setup_nfs() {
    local nfs_ip=${SERVERS["nfs"]}
    local mysql_ip=${SERVERS["mysql"]}
    log ">>> 正在配置NFS服务器 ($nfs_ip)"
    
    ssh_cmd $nfs_ip <<EOF
        # 安装依赖
        yum install -y nfs-utils rpcbind git
        
        # 创建共享目录
        mkdir -p /soft
        cd /soft
        
        # 克隆应用代码
        git clone https://gitee.com/egonlin/flask-web-app.git
        
        # 修改数据库配置
        sed -i 's/127.0.0.1/$mysql_ip/g' /soft/flask-web-app/conf/settings.py
        
        # 创建uWSGI配置文件
        cat > /soft/flask-web-app/uwsgi.ini <<EO
[uwsgi]
http = :8080
chdir = /soft/flask-web-app
module = my_app:app
processes = 4
threads = 2
EO
        
        # 配置NFS共享
        echo "/soft 192.168.1.0/24(rw,sync,all_squash)" > /etc/exports
        
        # 设置权限
        chmod -R 777 /soft
        
        # 启动服务
        systemctl enable rpcbind nfs-server
        systemctl start rpcbind nfs-server
        exportfs -a
EOF
}

# MySQL数据库配置
setup_mysql() {
    local mysql_ip=${SERVERS["mysql"]}
    log ">>> 正在配置MySQL数据库 ($mysql_ip)"
    
    # 安装MariaDB
    ssh_cmd $mysql_ip "yum install -y mariadb-server mariadb"
    ssh_cmd $mysql_ip "systemctl enable mariadb && systemctl start mariadb"
    
    # 安全设置和创建数据库
    ssh_cmd $mysql_ip <<EOF
        # 创建应用数据库和用户
        # 创建应用数据库和用户
         mysql -uroot -e "CREATE DATABASE IF NOT EXISTS testDB;"
        mysql -uroot -e "USE testDB; CREATE TABLE IF NOT EXISTS messages(id INT PRIMARY KEY AUTO_INCREMENT, text VARCHAR(15)) CHARACTER SET utf8mb4;"
        mysql -uroot -e "GRANT ALL ON testDB.* TO 'xxx'@'%' IDENTIFIED BY '123';"
        mysql -uroot -e "FLUSH PRIVILEGES;"    
EOF
}

# Web服务器配置
setup_web() {
    local nfs_ip=${SERVERS["nfs"]}
    local db_ip=${SERVERS["mysql"]}
    
    log ">>> 正在配置Web服务器"
    
    for host in web1 web2 web3; do
        local ip=${SERVERS[$host]}
        log "正在配置 $host ($ip)"
        
        ssh_cmd $ip <<EOF
            # 安装依赖
            yum install -y gcc* glibc* python3 python3-devel python3-pip nfs-utils
            pip3 install flask pymysql uwsgi
            
            # 挂载NFS共享
            mkdir -p /soft
            grep -q "$nfs_ip:/soft" /etc/fstab || echo "$nfs_ip:/soft /soft nfs defaults 0 0" >> /etc/fstab
            mount -a
            
            # 启动uWSGI服务
            uwsgi --ini /soft/flask-web-app/uwsgi.ini --daemonize /var/log/uwsgi.log &
EOF
    done
}

# 负载均衡配置
setup_lb() {
    local lb_ip=${SERVERS["lb"]}
    log ">>> 正在配置负载均衡器 ($lb_ip)"
    
    ssh_cmd $lb_ip "yum install -y nginx"
    
    # 生成Nginx配置
    local nginx_config="user nginx;

events {
    worker_connections 1024;
}

http {
    upstream web_app_servers {
        server ${SERVERS["web1"]}:8080 weight=1;
        server ${SERVERS["web2"]}:8080 weight=1;
        server ${SERVERS["web3"]}:8080 weight=1;
    }
    
    server {
        listen 80;
        location / {
            proxy_pass http://web_app_servers;
            proxy_set_header Host \$host;
            proxy_set_header X-Real-IP \$remote_addr;
        }
    }
}"
    
    # 部署Nginx配置
    ssh $SSH_OPTS $USER@$lb_ip "cat > /etc/nginx/nginx.conf <<EOF
$nginx_config
EOF"
    
    ssh_cmd $lb_ip "systemctl enable nginx && systemctl start nginx"
}

# 部署后检查
post_check() {
    log ">>> 正在进行部署后检查"
    
    # 检查NFS挂载
    for host in web1 web2 web3; do
        local ip=${SERVERS[$host]}
        ssh_cmd $ip "df -h | grep /soft" || log "[警告] $host 上的NFS挂载检查失败"
    done
    
    # 检查MySQL连接
    for host in web1 web2 web3; do
        local ip=${SERVERS[$host]}
        ssh_cmd $ip "python3 -c 'import pymysql; pymysql.connect(host=\"${SERVERS["mysql"]}\", user=\"$DB_USER\", password=\"$DB_PASS\", database=\"$DB_NAME\")'" || log "[警告] $host 无法连接MySQL"
    done
    
    # 检查负载均衡
    local lb_ip=${SERVERS["lb"]}
    ssh_cmd $lb_ip "curl -s http://localhost >/dev/null" || log "[警告] 负载均衡器服务检查失败"
}

# 主函数
main() {
    init_log
    
    log "=== 开始集群部署 ==="
    
    # 执行部署步骤
    setup_base           # 基础环境配置
    setup_nfs            # NFS共享存储
    setup_mysql          # MySQL数据库
    setup_web            # Web服务节点
    setup_lb             # 负载均衡器
    
    # 部署后检查
    post_check
    
    log "=== 集群部署完成 ==="
    echo ""
    echo "部署摘要:"
    echo " - 负载均衡器: http://${SERVERS["lb"]}"
    echo " - MySQL数据库: ${SERVERS["mysql"]} (用户: $DB_USER, 密码: $DB_PASS)"
    echo " - NFS服务器: ${SERVERS["nfs"]}:/soft"
    echo " - Web节点: ${SERVERS["web1"]}, ${SERVERS["web2"]}, ${SERVERS["web3"]}"
    echo ""
    echo "详细日志请查看 $LOG_FILE"
}

# 执行主函数
main "$@"